package free.spermwhales.gob;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

public enum DBMaster {
	INSTANCE;

	private static final String TABLE;
	private static final String UPDATE_REG;

	// utilizar getConnection() para acceder
	private Connection _conn;

	static {
		TABLE = "docmanager";
		UPDATE_REG = "UPDATE " + TABLE + " SET state = ? WHERE id = ?";
	}

	private DBMaster() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

			System.out.println("JDBC cargado OK.");
		} catch (Exception e) {
			System.out.println("Excepcion cargando JDBC: ");
			System.out.println(e.getStackTrace());
			System.exit(-1);
		}
	}

	private Connection getConnection() {
		if (_conn == null) {
			_conn = initConn();
		}

		return _conn;
	}

	public void shut() {
		try {

			_conn.close();
			_conn = null;

		} catch (Exception e) {
			System.out.println(e.getStackTrace());
			System.exit(-1);
		}
	}

	private Connection initConn() {
		Props config = Props.INSTANCE;

		String host = config.getConfig("host");
		String port = config.getConfig("puerto");
		String database = config.getConfig("base");

		Properties conInfo = new Properties();
		conInfo.setProperty("user", config.getConfig("usuario"));
		conInfo.setProperty("password", config.getConfig("password"));

		String url = "jdbc:oracle:thin:@" + host + ":" + port + ":" + database;

		Connection con = null;

		try {
			con = DriverManager.getConnection(url, conInfo);
		} catch (SQLException e) {
			System.out.println(e.getStackTrace());
			System.exit(-1);
		}

		return con;
	}

	public void actualizarRegistros(List<Registro> regs) {
		System.out.println("Actualizando " + regs.size()
				+ " registro/s en la base de datos...");

		for (Registro reg : regs) {
			actualizarRegistro(reg);
		}
	}

	public void actualizarRegistro(Registro reg) {
		try {
			PreparedStatement pst = getConnection()
					.prepareStatement(UPDATE_REG);

			pst.setString(1, reg.getState());
			pst.setLong(2, reg.getId());
			pst.execute();

			pst.close();
		} catch (SQLException e) {
			System.out.println("[ERR_UPDATE] " + reg.toString() + ": "
					+ e.getMessage());
		}
	}
}